package com.woorigil.social.domain.qna.parser;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import com.woorigil.social.HtmlUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.qna.Qna;
import com.woorigil.social.domain.qna.QnaBox;

@Component (value = "tmonQnaParser")
public class TmonQnaParser implements QnaParser {
	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.TM;
	}
	
	@Override
	public List<QnaBox> parse(String qnaUrl) {
		List<QnaBox> qnaBoxList = new ArrayList<QnaBox>();

		try {
			Document doc = Jsoup.connect(qnaUrl).userAgent("Mozilla").timeout(2000).get();
			Elements qnaElements = doc.select(".goods_qna");
			
			QnaBox qnaBox = new QnaBox(null);
			
			int count = 0;
			for (Element element : qnaElements) {
				if (count > 3) {
					break;
				}
				count++;
				
				Element qElement = element.select(".goods_qna_inner").first();
				if (qElement != null) {
					String qUser = "질문자";
					String qDate = qElement.select(".date").text();
					String qContent = HtmlUtils.br2nl(qElement.select(".qus_area p").html());
//					System.out.println(qUser + "/" + qDate + "/" + qContent);
					qnaBox = new QnaBox(new Qna(qUser, qDate, qContent));
				}
				
				for (Element aElement : element.select(".reply_area ul")) {
					if (aElement != null) {
						String aUser = aElement.select(".info strong").text();
						String aDate = aElement.select(".date").text();
						String aContent = HtmlUtils.br2nl(aElement.select(".reply").html());
//						System.out.println("\t" + aUser + "/" + aDate + "/" + aContent);
						qnaBox.addAnswer(new Qna(aUser, aDate, aContent));
					}
				}
				qnaBoxList.add(qnaBox);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qnaBoxList;
	}
}
